import time
import requests
import json
import os


class WeChat:
    
    def __init__(self):
        self.CORPID = os.getenv("CORPID")   #企业ID，在管理后台获取
        self.CORPSECRET = os.getenv("CORPSECRET")  #自建应用的Secret，每个自建应用里都有单独的secret
        self.AGENTID = os.getenv("AGENTID")  #应用ID，在后台应用中获取
        self.TOUSER = os.getenv("TOUSER")  # 接收者用户名,多个用户用|分割  @all为全部用户
        self.qyapi = os.getenv("QIAPI_PROXY", default = "qyapi.weixin.qq.com")
    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': self.CORPID,
                  'corpsecret': self.CORPSECRET,
                  }
        req = requests.post(url, params=values)
        data = json.loads(req.text)
        print(data["access_token"])
        return data["access_token"]

    def get_access_token(self):
        try:
            with open('access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('  '.join([str(cur_time), access_token]))
                return access_token
        else:
            cur_time = time.time()
            if 0 < cur_time - float(t) < 7260:
                return access_token
            else:
                with open('access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('  '.join([str(cur_time), access_token]))
                    return access_token

    def send_text_message(self, message):
        send_url = 'http://' + self.qyapi + '/cgi-bin/message/send?access_token=' + self.get_access_token()+"&debug=1"
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": message
            },
            "safe": "0"
        }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()   #当返回的数据是json串的时候直接用.json即可将respone转换成字典
        print(respone)
        return respone["errmsg"]

    def get_media_id(self, filetype, path):
        upload_file_url = 'https://' + self.qyapi + '/cgi-bin/media/upload?access_token={}&type={}'.format(self.get_access_token(), filetype)
        files = {filetype: open(path, 'rb')}
        file_upload_result = requests.post(upload_file_url, files=files).json()
        return file_upload_result["media_id"]

    # 发送图片消息
    def send_picture_message(self, media_id):
        send_picture_url = 'https://' + self.qyapi + '/cgi-bin/message/send?access_token={}'.format(self.get_access_token())
        data = {
            "touser": "@all",
            "msgtype": "image",
            "agentid": 1000002,
            "image": {
                "media_id": media_id
            },
            "safe": 0,
        }
        picture_message_res = requests.post(url=send_picture_url,data=json.dumps(data)).json()
        return picture_message_res
wechat = WeChat()

# if __name__ == '__main__':
#     wx = WeChat()
#     wx.send_text_message("Python程序调用企业微信API,从自建应用“告警测试应用”发送给管理员的消息!")
    # wx.send_picture_message(wx.get_media_id("image", "D:\\data\\jj20.jpg"))